﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace CProd
{
    public partial class frmViradas : Form
    {
        #region Declarações
        readonly SqlDataAdapter _daBobines = new SqlDataAdapter("Select * from Producao", frmEntrada.conn);
        SqlCommandBuilder _builder;
        readonly DataTable _dtBobines = new DataTable("dtBobines");
        readonly DataView _dvBobines = new DataView();
        readonly BindingSource _srcBobines = new BindingSource();
        private bool _newRecord = false;
        private char _turno;
        #endregion

        public frmViradas()
        {
            InitializeComponent();
        }

        private void frmViradas_Load(object sender, EventArgs e)
        {
            _builder = new SqlCommandBuilder(_daBobines);
            _daBobines.UpdateCommand = _builder.GetUpdateCommand();

            _daBobines.Fill(_dtBobines);
            _dvBobines.Table = _dtBobines;
            _srcBobines.DataSource = _dvBobines;
            GridBobines.DataSource = _srcBobines;

            if (_dtBobines.Rows.Count < 1)
            {
                btFirst.Enabled = false;
                btPrev.Enabled = false;
                btNext.Enabled = false;
                btLast.Enabled = false;
            }

            #region Columns Visibility
            GridBobines.Columns[0].Visible = false;
            GridBobines.Columns["Kgs"].Visible = false;
            GridBobines.Columns["Kgs NC"].Visible = false;
            GridBobines.Columns["Unid NC"].Visible = false;
            GridBobines.Columns["Unids"].Visible = false;
            GridBobines.Columns["Obs"].Visible = false;
            GridBobines.Columns["Obs"].Visible = false;
            #endregion

            #region Columns Sizes

            GridBobines.Columns["Ordem"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            int myWidth = GridBobines.Columns["Ordem"].Width;
            GridBobines.Columns["Ordem"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            GridBobines.Columns["Ordem"].Width = myWidth;

            GridBobines.Columns["Data"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            int myWidth2 = GridBobines.Columns["Data"].Width;
            GridBobines.Columns["Data"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            GridBobines.Columns["Data"].Width = myWidth2;

            #endregion

            txtKilos.DataBindings.Add("Text", _srcBobines, "Kgs");
            txtUnidades.DataBindings.Add("Text", _srcBobines, "Unids");
            txtUNC.DataBindings.Add("Text", _srcBobines, "Unid NC");
            txtKNC.DataBindings.Add("Text", _srcBobines, "Kgs NC");
            txtObs.DataBindings.Add("Text", _srcBobines, "Obs");
            txtDate.DataBindings.Add("Text", _srcBobines, "Data");
            txtTime.DataBindings.Add("Text", _srcBobines, "Hora");
        }

        private void btnSair_Click(object sender, EventArgs e)
        {
            Close();
        }

        #region Navegador
        private void btFirst_Click(object sender, EventArgs e)
        {
            _srcBobines.MoveFirst();
        }

        private void btLast_Click(object sender, EventArgs e)
        {
            _srcBobines.MoveLast();
        }

        private void btPrev_Click(object sender, EventArgs e)
        {
            _srcBobines.MovePrevious();
        }

        private void btNext_Click(object sender, EventArgs e)
        {
            _srcBobines.MoveNext();
        }
        #endregion

        private void frmViradas_Resize(object sender, EventArgs e)
        {
            ShowIcon = WindowState == FormWindowState.Maximized;
        }

        #region Validação Teclas
        private void txtKilos_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar) && e.KeyChar != ',' && e.KeyChar != '.' && !Char.IsControl(e.KeyChar)) e.Handled = true;
        }

        private void txtKNC_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar) && e.KeyChar != ',' && e.KeyChar != '.' && !Char.IsControl(e.KeyChar)) e.Handled = true;
        }

        private void txtUnidades_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar)) e.Handled = true;
        }

        private void txtUNC_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar)) e.Handled = true;
        }
        #endregion

        private void btDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Tem a certeza?", "Apagar Registo", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    _srcBobines.RemoveCurrent();
                    _daBobines.Update(_dtBobines);
                    MessageBox.Show("Registo Apagado com Sucesso");
                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }
            }
        }

        private void txtObs_TextChanged(object sender, EventArgs e)
        {
            txtObs.Text = txtObs.Text.Replace("\"", "");
        }

        private void btnInserir_Click(object sender, EventArgs e)
        {
            _newRecord = true;

            pnlInsert.Visible = true;

            txtDate.Focus();
            txtTime.Text = "";
            txtTurno.Text = "";
            txtTurno.Text = "";
            txtKilos.Text = "";
            txtKNC.Text = "";
            txtUnidades.Text = "";
            txtUNC.Text = "";
            txtObs.Text = "";
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            if (_newRecord)
            {
                DataRow dRow = _dtBobines.NewRow();

                #region "DataRow"

                dRow["Linha"] = txtLinha.Text;
                dRow["Data"] = txtDate.Text;
                dRow["Hora"] = txtTime.Text;
                dRow["Virada"] = txtVirada.Text;
                dRow["Turno"] = txtTurno.Text.Trim();
                dRow["Ordem"] = txtOrdem.Text;
                dRow["Kgs"] = txtKilos.Text;
                dRow["Unids"] = txtUnidades.Text;
                dRow["Kgs NC"] = txtKNC.Text;
                dRow["Unid NC"] = txtUNC.Text;
                dRow["Obs"] = "\"" + txtObs.Text + "\"";
                dRow["Operador"] = txtOperador.Text;

                #endregion

                _dtBobines.Rows.Add(dRow);
            }
            else _srcBobines.EndEdit();
            
            _daBobines.Update(_dtBobines);
            pnlInsert.Visible = false;
            MessageBox.Show("Gravado com sucesso", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }


        private void txtTime_TextChanged(object sender, EventArgs e)
        {
            if (txtTime.Text.Trim().Length == 5) calculaTurno();
        }

        private void txtDate_ValueChanged(object sender, EventArgs e)
        {
            if (txtTime.Text.Trim().Length == 5) calculaTurno();
        }

        private void calculaTurno()
        {
            DateTime time = DateTime.Parse(txtTime.Text);

            const string turno1 = "DDCCCBBBBAAACCCCDDDAAAABBBDD";
            const string turno2 = "AAADDDDDDDBBBBBBBCCCCCCCAAAA";
            const string turno3 = "CBBBAAAACCCDDDDAAABBBBDDDCCC";

            double difDias = Math.Truncate(DateTime.Parse(txtDate.Text).Subtract(Convert.ToDateTime("24-12-2006")).TotalDays);
            int y = Convert.ToInt32(difDias - Math.Truncate(Math.Truncate(difDias / 28) * 28));

            if (y == 0) y = 27;

            if (time >= DateTime.Parse("00:00") && time <= DateTime.Parse("08:00"))
                _turno = turno1[y];
            if (time >= DateTime.Parse("08:01") && time <= DateTime.Parse("16:00"))
                _turno = turno2[y];
            if (time >= DateTime.Parse("16:01") && time <= DateTime.Parse("23:59"))
                _turno = turno3[y];

            txtTurno.Text = _turno.ToString();
        }

        private void frmViradas_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Escape || !pnlInsert.Visible) return;

            _newRecord = false;
            pnlInsert.Visible = false;
            _dtBobines.Clear();
            _daBobines.Fill(_dtBobines);
        }
    }
}